<?php

namespace app\admin\controller\maichen;

use app\admin\model\Customer as CustomerModel;
use app\common\controller\Backend;
use lemo\helper\ExcelHelper;

class Customer extends Backend
{
    protected $modelClass = CustomerModel::class;

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 导入Excel
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            $file = request()->file('file');
            if (!$file) {
                return json(['code' => 1, 'msg' => '请选择文件']);
            }

            try {
                // 验证文件
                validate(['file' => 'fileSize:10240|fileExt:xlsx,xls'])->check(['file' => $file]);
                
                // 保存文件
                $savename = \think\facade\Filesystem::disk('public')->putFile('excel', $file);
                $filePath = public_path() . 'storage/' . $savename;

                // 读取Excel
                $data = \lemo\helper\ExcelHelper::import($filePath, 2); // 从第2行开始读取数据
                halt($data);
                // 处理数据
                $success = 0;
                $error = 0;
                foreach ($data as $row) {
                    try {
                        $customer = new CustomerModel();
                        $customer->name = $row[0] ?? ''; // 客户名称
                        $customer->phone = $row[1] ?? ''; // 联系电话
                        $customer->address = $row[2] ?? ''; // 地址
                        $customer->save();
                        $success++;
                    } catch (\Exception $e) {
                        $error++;
                    }
                }

                // 删除临时文件
                @unlink($filePath);

                return json([
                    'code' => 0,
                    'msg' => "导入完成，成功：{$success}条，失败：{$error}条",
                    'data' => ['filename' => $file->getOriginalName()]
                ]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
        }

        return json(['code' => 1, 'msg' => '非法请求']);
    }
} 